const express = require('express');
const router = express.Router();
const db = require('../config/database');
const { body, validationResult } = require('express-validator');
const { authenticateToken, generateString, encryptPhone, decryptPhone, logUserOperation } = require('../untils/untils');
const dayjs = require('dayjs')
const { cryptoHelper } = require('../config/global');


// 客户信息接口
// 参数实例:
// {
//     "churn_id": "C2025070400001",
//     "churn_date": "2025-07-04",
//     "reason": "流失原因"
// }
router.get('/', authenticateToken, async (req, res) => {
    const { churn_id, cust_name, mobile } = req.query;
    let sql = 'SELECT * FROM churn_record';
    if (churn_id) {
        sql += ` WHERE churn_id LIKE '%${churn_id}%'`;
    }
    if (cust_name) {
        sql += ` WHERE cust_name LIKE '%${cust_name}%'`;
    }
    if (mobile) {
        sql += ` WHERE mobile_hash = '${cryptoHelper.hash(mobile)}'`;
    }

    try {
        const [customers] = await db.execute(sql);
        const [employees] = await db.execute(
            'SELECT * FROM employee where status = "在职"'
        );
        // 将手机号解密并排除mobile_hash字段;
        // 将emp_id翻译为员工姓名并放入员工对象
        customers.forEach(item => {
            item.churn_date = dayjs(item.churn_date).format('YYYY-MM-DD');
            item.mobile = cryptoHelper.decrypt(item.mobile).replace(/^(\d{3})\d+(\d{4})$/, '$1****$2');
            delete item.mobile_hash;
            item.emp = employees.find(emp => emp.emp_id === item.emp_id);
        });

        await logUserOperation(req, '查询', '获取流失记录', '获取流失记录成功', '成功');

        res.json({
            success: true,
            message: '获取客户信息成功',
            data: customers
        });
    } catch (error) {
        console.error('获取客户信息失败:', error);
        await logUserOperation(req, '查询', '获取流失记录', '获取流失记录失败', '失败', error.message);
        res.status(500).json({
            success: false,
            message: '获取客户信息失败'
        });
    }
});

// 更新客户信息接口
// 参数实例:
// {
//     "churn_id": "C2025070400001",
//     "reason": "流失原因",
//     "emp_id": "E2025070400001",
//     "strategy": "流失策略",
//     "recovered": "是否挽回"
// }
router.post('/update', authenticateToken, async (req, res) => {
    try {
        const { cust_id, churn_id, reason, emp_id, strategy, recovered } = req.body;

        // 验证必需参数
        if (!churn_id) {
            return res.status(400).json({
                success: false,
                message: '流失记录ID不能为空'
            });
        }

        if (!cust_id) {
            return res.status(400).json({
                success: false,
                message: '客户ID不能为空'
            });
        }

        // 更新流失记录
        const updateChurnSql = `UPDATE churn_record SET reason = ?, emp_id = ?, strategy = ?, recovered = ? WHERE churn_id = ?`;
        const updateChurnParams = [reason, emp_id, strategy, recovered, churn_id];

        const [churnResult] = await db.execute(updateChurnSql, updateChurnParams);

        // 检查是否更新成功
        if (churnResult.affectedRows === 0) {
            return res.status(404).json({
                success: false,
                message: '流失记录不存在'
            });
        }

        // 如果客户已恢复，更新客户状态
        if (recovered === '是') {
            const updateCustomerSql = `UPDATE customer SET is_public_pool = '否', last_followup = NOW() WHERE cust_id = ?`;
            const updateCustomerParams = [cust_id];

            const [customerResult] = await db.execute(updateCustomerSql, updateCustomerParams);

            if (customerResult.affectedRows === 0) {
                console.warn(`⚠️ 客户 ${cust_id} 不存在或状态更新失败`);
            } else {
                console.log(`✅ 客户 ${cust_id} 已从公海恢复`);
            }
        }

        await logUserOperation(req, '更新', '更新流失记录', '更新流失记录成功', '成功');
        res.json({
            success: true,
            message: '更新流失记录成功',
            data: {
                churnUpdated: churnResult.affectedRows,
                customerRecovered: recovered === '是'
            }
        });
    } catch (error) {
        console.error('更新流失记录失败:', error);
        await logUserOperation(req, '更新', '更新流失记录', '更新流失记录失败', '失败', error.message);
        res.status(500).json({
            success: false,
            message: '更新流失记录失败',
            error: error.message
        });
    }
})


// 获取修改初始化
router.get('/get_update_init', authenticateToken, async (req, res) => {
    const { churn_id } = req.query;
    try {
        const [result] = await db.execute(
            'SELECT * FROM churn_record where churn_id = ?',
            [churn_id]
        );

        result.forEach(item => {
            item.mobile = cryptoHelper.decrypt(item.mobile);
        });

        res.json({
            success: true,
            message: '获取修改初始化成功',
            data: result
        });
    } catch (error) {
        console.error('获取修改初始化失败:', error);
        await logUserOperation(req, '查询', '获取修改初始化', '获取修改初始化失败', '失败', error.message);
        res.status(500).json({
            success: false,
            message: '获取修改初始化失败',
            error: error.message
        });
    }
})

// 获取跟进人员
router.get('/get_followup_staff', authenticateToken, async (req, res) => {
    try {
        let [result] = await db.execute(
            'SELECT * FROM employee where status = "在职"'
        );
        result = result.map(item => {
            return {
                key: item.emp_id,
                name: item.emp_name
            }
        });
        await logUserOperation(req, '查询', '获取流失记录', '获取流失记录成功', '成功');
        res.json({
            success: true,
            message: '获取跟进人员成功',
            data: result
        });
    } catch (error) {
        console.error('获取跟进人员失败:', error);
        await logUserOperation(req, '查询', '获取流失记录', '获取流失记录失败', '失败', error.message);
        res.status(500).json({
            success: false,
            message: '获取跟进人员失败',
            error: error.message
        });
    }
});



module.exports = router;
